package top.codedance.iotp.iot.sdk;

import top.codedance.iotp.iot.sdk.entity.DistributedRegistyUris;
import top.codedance.iotp.iot.sdk.po.async.CommonParam;
import top.codedance.iotp.loadblance.common.AlgorithmType;
import org.java_websocket.handshake.ServerHandshake;

public class DistributedWsService extends AbstractWsDistributedService {

    private WsClient client = null;
    public DistributedWsService(DistributedRegistyUris registyHosts, String route, String deviceId) {
        super(registyHosts, route, deviceId);
    }

    public DistributedWsService(DistributedRegistyUris registyHosts, String route, AlgorithmType at, String deviceId) {
        super(registyHosts, route, at, deviceId);
    }

    @Override
    public void run(CommonParam commonParam, WsCallbackAdapter callbacker) {
        commonParam.setDeviceId(deviceId);
        client = this.request(new WsCallbacker() {
            public void onOpen(WsContextAdapter context, ServerHandshake shake) {
                String s = commonParam.toString();
                context.send(s);
                callbacker.onOpen(context, commonParam, shake);
            }

            public void onMessage(final WsContextAdapter context, String body) {
                callbacker.onMessage(context, commonParam, body);
            }

            public void onClose(WsContextAdapter context, int var1, String var2, boolean var3) {
                callbacker.onClose(context, commonParam, var1, var2, var3);
            }

            public void onError(WsContextAdapter context, Exception e) {
                callbacker.onError(context, commonParam, e);
            }
        });
    }

    public void send(String body){
        client.send(body);
    }

    @Override
    public void stop() {
        if(client != null){
            client.destory();
        }
    }

    public void waiting(){
        Object lock = new Object();
        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("WsClient over.");
            }
        }
        stop();
    }
}
